﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Kooboo.Web.Mvc.Paging;

namespace Kooboo.Web.Areas.Commerce.Controllers
{
    using Kooboo.Commerce;
    using Kooboo.Web.Mvc;
    using Kooboo.Commerce.Contexts.Products;

    public class ProductReviewController : ManagementController
    {
        #region Index
        public ActionResult Index(int? page, int? pageSize)
        {
            var currentPageIndex = page ?? 1;
            var currentPageSize = pageSize ?? Configuration.PageSize;

            var query = this.Actor.QueryProductReviews()
                .OrderByDescending(i => i.Id);

            ViewData["delete_action"] = this.Url.Action<ProductReviewController>(i => i.Delete(null));
            ViewData["publish_action"] = this.Url.Action<ProductReviewController>(i => i.Publish(UrlParameter<int>.Empty));

            ViewData["Pager"] = query.BuildPagerModel(this.Url.Action<ProductReviewController>(i => i.Index(null, null)), currentPageIndex, currentPageSize);

            String currentUrl = this.Request.Url.ToString();
            var productUrl = this.Url.Action<ProductController>(i => i.Edit(-1));
            var customerUrl = this.Url.Action("Edit", "Customer", new { id = -1, returnUrl = currentUrl });

            ViewData["Reviews"] = query.Skip((currentPageIndex - 1) * currentPageSize).Take(currentPageSize)
                .Select(i => new
                {
                    i.Id,
                    i.IsPublished,
                    ProductName = i.Product.Name,
                    ProductUrl = productUrl.Replace("-1", i.Product.Id.ToString()),
                    CustomerName = i.Customer.FirstName + " " + i.Customer.MiddleName + " " + i.Customer.LastName,
                    CustomerUrl = customerUrl.Replace("-1", i.Customer.Id.ToString()),
                    CreateDate = i.CreateDate.ToString(),
                    i.Remark,
                    Rate = (int)i.Rate,
                })
                .ToArray()
                .SerializeToJson();


            return View();
        }

        #endregion


        [HttpPost]
        public ActionResult Publish(int id)
        {
            var review = this.Actor.QueryProductReviews().Where(i => i.Id == id).FirstOrDefault();
            if (review.IsPublished == false)
            {
                review.IsPublished = true;
            }
            else
            {
                review.IsPublished = false;
            }
            this.Actor.Put(review);

            return Json(true);
        }

        [HttpPost]
        public ActionResult Delete(IProductReview review)
        {
            this.Actor.Delete(review);
            return Json(true);

        }


    }
}
